
var param = {}, formId = 'queryForm', url = "/openx/posting/postingQueryService/queryAllRecords";

var orderCode = null;

var days = 30;

let topChannelCodeList = [];

//点击查询按钮调用
$.openx.query = function () {
	var createStartTime = new Date($("#createStartTime").val().replace(/\-/g, "\/"));
    var createEndTime = new Date($("#createEndTime").val().replace(/\-/g, "\/"));
    getDaysByMonth(createStartTime.getFullYear(),createStartTime.getMonth() + 1);
    if(createStartTime >createEndTime)
    {
        layer.msg('开始时间不能大于结束时间！');
        return false;
    }
    createStartTime = new Date(createStartTime.setDate(createStartTime.getDate()+days));
	if(createStartTime < createEndTime){
		layer.msg('选择的时间区间必须在'+days+'天以内');
        return false;
	}
    param.bean = $.openx.getJsonObj(formId);
    if(param.bean.topChannelCode){
        let data = $("#channelCode").yfChannel("getData");
        let channels = [];
        if (data.length > 0) {
            data.forEach(item => {
                channels.push(item.displayChannel);
            })
        };
        param.bean.channelCodes = channels;
    }else {
        param.bean.channelCodes = [];
    }
    param.bean.storeCodes = [];
    $.openx.tableRefresh(url, param);
}


//初始化日期控件时间
layui.use('laydate', function () {
    var laydate = layui.laydate;
    document.getElementById('createStartTime').value = laydate.now() + ' 00:00:00';
    document.getElementById('createEndTime').value = laydate.now() + ' 23:59:59';
    initTopChannel("topChannelCode");
    var data = $.openx.getJsonObj(formId);
    data.storeCodes = [];
    param.bean = data;
    $.openx.initTable("table", url, param);
});

/**
 * 格式化下单时间
 */
function createTimeFormat(value, row) {
    return $.openx.formatDate(new Date(value), "yyyy-MM-dd hh:mm");
}

function formatCode(value, row) {
    if(value) {
        return '\'' + value;
    } else {
        return '';
    }
}

//格式化订单详情按钮
function operationFormat(value, row) {

    //是否已下账
    var status = (row.pStatus === "SUCCESS" || row.topChannelCode === "POS") ? true : false;

    //下账按钮是否显示
    var html = "<a href=\'javascript:void(0)\' onclick =\'javascript:postingAgain(" + (!status ? JSON.stringify(row) : null) + ")\'>" +
        "<button type='button'" + (!status ? "" : "disabled") + "   class='btn btn-outline " + (!status ? 'btn-primary' : 'btn-default') + " btn-xs'> " + (!status ? "重新下账" : "重新下账") + "</button> "
    "<a>";


    return html;

}

function resetForm(){
    $('#queryForm')[0].reset();
    $("#channelCode").yfChannel("reset");
    let laydate = layui.laydate;
    console.log(laydate.now().split(' ')[0]);
    document.getElementById('createStartTime').value = laydate.now().split(' ')[0] + ' 00:00:00';
    document.getElementById('createEndTime').value = laydate.now().split(' ')[0] + ' 23:59:59';
    let data = $.openx.getJsonObj(formId);
    data.storeCodes = [];
    param.bean = data;
    $.openx.initTable("table", url, param);
    $.openx.query();
}

var previousObj = $("button[name='billStatus']")[0];
$("button[name='billStatus']").on('click', function (e) {
    var $this = e.currentTarget;
    $("input[name='billStatus']").val($this.value);
    if (previousObj != $this) {
        $($this).find('i').addClass("glyphicon glyphicon-ok-sign")
        $(previousObj).find('i').removeClass('glyphicon glyphicon-ok-sign');
    }
    previousObj = $this;
    $.openx.query();
});

function postingAgain(row){
    ajax(jot_posting_server + "/posting/postingService", "sendPostingAgain").callx({
        orderCode: row.orderCode,
        posCode:row.posCode,
        billType:row.billType,
        onResult: function (result) {
            if(result === 'SUCCESS'){
                layer.msg('重新下账处理成功');
                layer.closeAll('loading');
                setTimeout(function () {$.openx.tableRefresh(null,null,true)}, 2000);
            }else{
                layer.msg('重新下账处理失败');
            }
        },
        onError: function (error) {
            layer.msg('重新下账处理失败');
        }
    });
}

function getDaysByMonth(year,month){
	var monthDays;
	//判断月份大小获得天数
	if(month==='1' || month==='3' || month==='5' ||month==='7' ||month==='8' ||month==='10' ||month==='12'){
		monthDays=31;
	}else if(month==='4' ||month==='6' ||month==='9' ||month==='11'){
		monthDays=30;
	}else{
		monthDays=28;
		//判断当前选择的年份是否是闰年
		if((year % 100 === 0 && year % 400 === 0)|| year%4===0){
			monthDays=29;
		}
	}
	days=monthDays;
	return days;
}
//顶级渠道变更
async function changeToChannelCode(topChannelCode) {
    if (!topChannelCode) {
        layer.msg("请选择顶级渠道");
        return;
    }
    let options = {
        service: '/boss/channelService',
        method: "/listChannelTree",
        refreshMethod: "refreshChannelTree",
        importMethod: "importChannelCode",
        filter: 'leaves',
        topChannelCode: topChannelCode,
        isSearch: true,
        isImport: true,
    };
    $("#channelCode").yfChannel(options);
    $("#channelCode").attr("disabled", false);
}
//初始化顶级渠道
async function initTopChannel(second) {
    $X("/boss/channelService", "listAllTopChannel").callx({
        onResult: function (data) {
            if (data) {
                $("#" + second).append("<option value='''>" + '请选择' + "</option>");
                topChannelCodeList = data;
                data.forEach(item => {
                    $("#" + second).append("<option value=\"" + item.channelCode + "\">" + item.name + "</option>");
                })
            } else {
                layer.msg("无信息")
            }
        },
        onError: function (error) {
            let res = JSON.parse(error);
            layer.msg(res.message)
        }
    });
}
/**
 * New Openx js client, more modern ! 2015-05-19
 */
function ajax(mapping, method) {
    var _m = mapping;
    var _t = method;
    this.callx = function (data, timeout) {
        var url = _m + '/' + _t;
        if (openx.isNull(data)) {
            data = {};
        }
        openx.invoke(url, openx.conf()['type'], data, timeout, data.onResult, data.onError);
    };
    return this;
}

